<?php

namespace app\common\model;


class AttachmentGroupModel extends BaseModel
{

  protected $table = 'attachment_group';

  //开启自动写入时间戳
  protected $autoWriteTimestamp = false;

  /**
   * 添加
   * @param $data
   * @return ConfigModel|\think\Model
   * @throws \Exception
   */
  public function add($data)
  {
    $info = $this->where('group_name', $data['group_name'])->find();
    if ($info) abort(500, '分组名称已存在');
    return self::create($data);
  }

  /**
   * 编辑
   * @param $data
   * @return AttachmentGroupModel
   * @throws \Exception
   */
  public function edit($data)
  {
    $info = $this->where('id', $data['id'])->find();
    if ($data['group_name'] != $info['group_name'] && $this->where('group_name', $data['group_name'])->find()) {
      abort(500, '分组名称已存在');
    }
    return self::update($data);
  }

  /**
   * 删除分组
   * @param $id
   * @return bool
   * @throws \Exception
   */
  public function del($id)
  {
    $files = AttachmentModel::where('group_id', $id)->find();
    if (!empty($files)) abort(500, '分组下还存在文件，不允许删除！');
    $this->where('id', $id)->delete();
    return true;
  }

  /**
   * 格式化列表
   * @param array $list
   * @param $fileType
   * @return mixed
   */
  public function _formatList($list,$fileType=null)
  {
    $map = [];
    if(!empty($fileType)) $map[] = ['file_type','in',$fileType];
    $groupCount = AttachmentModel::group('group_id')->where('file_type','in',$fileType)->column('count(*)', 'group_id');
    foreach ($list as $k => $v) {
      $list[$k]['file_num'] = 0;
      if (isset($groupCount[$v['id']])) {
        $list[$k]['file_num'] = $groupCount[$v['id']];
      }
    }
    $list[] = ['id' => 0, 'group_name' => '无分组', 'file_num' => $groupCount[0] ?? 0];
    return $list;
  }


}
